<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2018/8/28
 * Time: 上午10:01
 */

namespace Common\Service;
use King\Model\gradeModel;
use King\Model\memberModel;
use King\Model\moneylogModel;
use King\Model\orderModel;
use Think\Exception;

/**
 * 升级处理
 * Class PromoteService
 * @package Common\Service
 */
class PromoteService extends BaseService
{
    public $orderModel;
    public $userModel;
    public $gradeInfo;
    public $moneyLogModel;
    public static $grade_Partner=1;//合伙人
    public static $grade_City=2;//城市合伙人
    public static $grade_Official=3;//官方合伙人
    public function __construct()
    {
        $this->orderModel=new orderModel();
        $this->userModel=new memberModel();
        $this->moneyLogModel=new moneylogModel();
        $gradeModel=new gradeModel();
        $gradeInfo=$gradeModel->select();
        foreach ($gradeInfo as $key=>$value){
            $this->gradeInfo[$value['grade_id']]=$value['condition'];
        }

    }

    /**
     * 处理订单分佣金
     * @param $order_id
     * @return bool
     */
    public function processingOrders($order_id){
        try{
                $orderInfo=$this->orderModel->where(array('order_id'=>$order_id))->find();
                if(!$orderInfo || $orderInfo['checked']!=1){
                    LogInfoService::S()->writeLog('PromoteService','queryOrder','订单状态不正确：'.$order_id);
                    return false;
                }
                if($orderInfo['balance']==1){
                    LogInfoService::S()->writeLog('PromoteService','queryOrder','订单已结算，重复结算：'.$order_id);
                    return false;
                }
                //取出订单总金额
                $countMoney=$orderInfo['pay_orgmoney'];
                if($countMoney<$this->gradeInfo[self::$grade_Partner]){//小于普通合伙人
                    LogInfoService::S()
                        ->writeLog('PromoteService',
                            'queryOrder',
                            '未查询到该订单的等级信息，无法升级,订单编号：'.$order_id);
                    return false;
                }
                if($this->gradeInfo[self::$grade_Partner]<=$countMoney &&$countMoney<$this->gradeInfo[self::$grade_City]){
                    $grade=self::$grade_Partner;
                }
                elseif($this->gradeInfo[self::$grade_City]<=$countMoney &&$countMoney<$this->gradeInfo[self::$grade_Official]){//查询到等级金额
                    $grade=self::$grade_City;
                }elseif($this->gradeInfo[self::$grade_Official]<=$countMoney){
                    $grade=self::$grade_Official;
                }
                $memberInfo=$this->userModel->where(array('uid'=>$orderInfo['uid']))->find();
                //分佣逻辑
            $oneUid=$memberInfo['refer_uid'];//一级代理
            $twoUid=self::findRefer($oneUid);//二级代理
            $oneCityUid=self::S()->findPartner($memberInfo['refer_uid'],self::$grade_City);//第一个城市合伙人
            if($oneCityUid){
                $oneOfficialUid=self::S()->findPartner($oneCityUid,self::$grade_Official);
                if(!$oneOfficialUid){//没有官方合伙人
                    //向上的平级城市合伙人分两级
                    $referUid=self::findRefer($oneCityUid);
                    $twoCityUid=self::findPartner($referUid,self::$grade_City);//城市合伙人的平级分
                    if($twoCityUid){
                        $ThirdReferUid=self::findRefer($twoCityUid);
                        $ThirdCityUid=self::findPartner($ThirdReferUid,self::$grade_City);//城市合伙人的第二级分佣
                    }
                }else{//存在官方合伙人 --
                    //查找前面两级官方合伙人
                    $twoOfficialReferUid=self::findRefer($oneOfficialUid);
                    $twoOfficialUid=self::findPartner($twoOfficialReferUid,self::$grade_Official);//官方合伙人的第二级分佣
                    if($twoOfficialUid){
                        $ThirdOfficialReferUid=self::findRefer($twoOfficialUid);
                        $ThirdOfficialUid=self::findPartner($ThirdOfficialReferUid,self::$grade_City);//官方合伙人的第二级分佣
                    }
                }
            }
            M()->startTrans();
            switch ($grade){
                case self::$grade_Partner://等级一：合伙人
                    $oneUidMoney=5200;//一级合伙人拿去分佣
                    $twoUidMoney=1341;//二级拿取分佣
                    $oneCityUidMoney=800;//上级城市合伙人
                    $twoCityUidMoney=100;//平级城市合伙人
                    $ThirdCityUidMoney=100;//平级城市合伙人
                    $oneOfficialUidMoney=800;//官方合伙人
                    $twoOfficialUidMoney=100;//平级官方合伙人
                    $ThirdOfficialUidMoney=100;//平级官方合伙人
                    break;
                case self::$grade_City:
                case self::$grade_Official:
                    $oneUidMoney=$countMoney*0.08;//一级合伙人拿去分佣
                    $twoUidMoney=$countMoney*0.03;//二级拿取分佣
                    $oneCityUidMoney=$countMoney*0.06;//上级城市合伙人
                    $twoCityUidMoney=$countMoney*0.02;//平级城市合伙人
                    $ThirdCityUidMoney=$countMoney*0.02;//平级城市合伙人
                    $oneOfficialUidMoney=$countMoney*0.06;//官方合伙人
                    $twoOfficialUidMoney=$countMoney*0.03;//平级官方合伙人
                    $ThirdOfficialUidMoney=$countMoney*0.03;//平级官方合伙人
                    break;
                default:
                    LogInfoService::S()->writeLog('PromoteService','queryOrder','订单金额不允许分佣金');
                    return false;
                    break;
            }
            //一级代理分5200
            $oneUidResult=self::makeMoney($oneUid,$oneUidMoney);
            if(!$oneUidResult){//分拥错误
                M()->rollback();
            }
            $addMoneyLog[]=array(
                'uid'=>$oneUid,
                'content'=>'[凝胶 一级分放佣金]',
                'lock_money'=>$oneUidMoney
            );
            if($twoUid){
                //二级代理分 1314
                $twoUidResult=self::makeMoney($twoUid,$twoUidMoney);
                if(!$twoUidResult){//分拥错误
                    M()->rollback();
                }
                $addMoneyLog[]=array(
                    'uid'=>$twoUid,
                    'content'=>'[凝胶-二级分放佣金]',
                    'lock_money'=>$twoUidMoney
                );
            }
            //向上的城市合伙人分800
            if($oneCityUid){
                $oneCityUidResult=self::makeMoney($oneCityUid,$oneCityUidMoney);
                if(!$oneCityUidResult){//分佣错误
                    M()->rollback();
                }
                $addMoneyLog[]=array(
                    'uid'=>$oneCityUid,
                    'content'=>'[凝胶-城市合伙人分放佣金]',
                    'lock_money'=>$oneCityUidMoney
                );

                if($oneOfficialUid){//存在官方合伙人
                    $oneOfficialUidResult=self::makeMoney($oneOfficialUid,$oneOfficialUidMoney);
                    if($oneOfficialUidResult){
                        $addMoneyLog[]=array(
                            'uid'=>$oneOfficialUid,
                            'content'=>'[凝胶-官方合伙人分放佣金]',
                            'lock_money'=>$oneOfficialUidMoney,
                        );
                    }
                    if($twoOfficialUid){
                        $twoOfficialUidResult=self::makeMoney($twoOfficialUid,$twoOfficialUidMoney);
                        if($twoOfficialUidResult){
                            $addMoneyLog[]=array(
                                'uid'=>$twoOfficialUid,
                                'content'=>'[凝胶-官方合伙人平级分放佣金]',
                                'lock_money'=>$twoOfficialUidMoney,
                            );
                        }
                    }
                    if($ThirdOfficialUid){
                        $ThirdOfficialUidResult=self::makeMoney($ThirdOfficialUid,$ThirdOfficialUidMoney);
                        if($ThirdOfficialUidResult){
                            $addMoneyLog[]=array(
                                'uid'=>$ThirdOfficialUid,
                                'content'=>'[凝胶-官方合伙人平级分放佣金]',
                                'lock_money'=>$ThirdOfficialUidMoney,
                            );
                        }
                    }
                }else{//不存在官方合伙人
                    if($twoCityUid){
                        $twoCityUidResult=self::makeMoney($twoCityUid,$twoCityUidMoney);
                        if($twoCityUidResult){
                            $addMoneyLog[]=array(
                                'uid'=>$twoCityUid,
                                'content'=>'[凝胶-城市合伙人平级分放佣金]',
                                'lock_money'=>$twoCityUidMoney,
                            );
                        }
                    }
                    if($ThirdCityUid){
                        $ThirdCityUidResult=self::makeMoney($ThirdCityUid,$ThirdCityUidMoney);
                        if($ThirdCityUidResult){
                            $addMoneyLog[]=array(
                                'uid'=>$ThirdCityUid,
                                'content'=>'[凝胶-城市合伙人平级分放佣金]',
                                'lock_money'=>$ThirdCityUidMoney,
                            );
                        }
                    }
                }
            }

            foreach ($addMoneyLog as $key=>$v){
                $addMoneyLog[$key]['logtype']=1;//日志类型 收入
                $addMoneyLog[$key]['order_id']=$order_id;//订单id
                $addMoneyLog[$key]['order_uid']=$orderInfo['uid'];//下单人uid
                $addMoneyLog[$key]['wintype']=16;//$orderInfo['uid'];凝胶
                $addMoneyLog[$key]['order_paymoney']=$countMoney;//$orderInfo['uid'];//订单总金额

            }
                //批量写入分拥日志
                $this->moneyLogModel->addAll($addMoneyLog);
                $re=$this->userModel->where(array('uid'=>$orderInfo['uid']))->save(array('grade_id'=>$grade));
                //保存该用户等级
                if($re===false){
                    M()->rollback();
                    return false;
                }else{
                    //修改订单状态成已结算
                    $result=$this->orderModel->where(array('order_id'=>$order_id))->save(array('balance'=>1));
                    M()->commit();
                }
                return true;
        }catch (Exception $ex){
            echo 'Exception:'.$ex->getMessage();
            return false;
        }
    }

    /**
     * 根据类型查找合伙人
     * @param $uid
     * @param $grade
     * @return bool
     */
    public function findPartner($uid,$grade){
        do{
            $userInfo=$this->userModel->where(array('uid'=>$uid))->find();
            if(!$userInfo){
                break;
            }
            if($userInfo['grade_id']==$grade){
                return $userInfo['uid'];
                break;
            }else{
                if(!$userInfo['refer_uid']){
                    break;
                }
                $uid=$userInfo['refer_uid'];
            }
        }while(true);
        return false;
    }

    /**
     * 打款给用户
     * @param $uid
     * @param $money
     * @return bool
     */
    public function makeMoney($uid,$money){
        return $this->userModel->where(array('uid'=>$uid))->setInc('lock_money',$money);
    }

    public function moneyLog($uid,$content,$order_id,$order_uid,$order_paymoney,$wintype=16){//凝胶
        $add['uid']=$uid;
        $add['content']=$content;
        $add['order_id']=$order_id;
        $add['order_uid']=$order_uid;
        $add['wintype']=$wintype;
        $add['order_paymoney']=$order_paymoney;
        return $this->moneyLogModel->add($add);
    }
    //查找上级用户
    public function findRefer($uid){
        return $this->userModel->where(array('uid'=>$uid))->getField('refer_uid');
    }

}